<?php
namespace app\common\model\revenue_ap;
use app\api\controller\Pub;
use app\common\model\user\User;
use app\common\model\power\Rolepower;
use app\common\model\company\Contract;
use app\common\model\orderhawa\HawaList;
use think\Model;

//服务费档案信息
class RapList extends Model
{
    protected $table = 'revenue_account_period_list';
    protected $pk    = 'RAPListId';

    const STATEINT  = 0; //初始化 待回款
    const STATEING  = 1; //进行中
    const STATEEND  = 2; //结束回款
    const STATESTOP = 3; //回款停止
    /**
     * 状态分类
     * @param string $value [description]
     * @return [type]        [description]
     */
    public static function getStatusText($value = '')
    {
        $status = [0 => '待回款', 1 => '回款中', 2 => '回款结束', 3 => '回款停止'];
        if ($value !== '') {
            return $status[$value];
        }
        return $status;
    }

    public function getExpectedTimeAttr($value)
    {
        if($value=='0000-00-00 00:00:00'){
            return '';
        }
        return $value;
    }

    /**
     * 创建回款档案列表
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function user_create($idata)
    {   
        // //判断重复
        // $sb = RapList::where('IsDelete','<>','1')->where('Type',$idata['Type'])->where('CorrelationId',$idata['CorrelationId'])->find();
        // if(!empty($sb)){
        //     return moerr('关联信息中已经存在回款记录');
        // }

        //检测原表数据
        switch ($idata['Type']) {
            case 'contract':
                $sb = Contract::get($idata['CorrelationId']);
                if(empty($sb)){return moerr('缺少关联的合同信息');}
                $idata['TotalCost'] = $sb['ContractCost'];
                break;
            case 'orderhawa':
                $sb = HawaList::get($idata['CorrelationId']);
                if(empty($sb)){return moerr('缺少关联的订单信息');}
                $idata['TotalCost'] = $sb['TotalCost'];
                break;
            default:
                return moerr('暂不支持此类型订单挂账');
                break;
        }

        if(empty($idata['TotalCost'])){
            return moerr('订单总金额为0无需挂账');
        }
        $rebate               = new RapList();
        $rebate->State        = RapList::STATEINT;
        $rebate->CreateTime   = date('Y-m-d H:i:s', time());
        $rebate->CreateUserId = Pub::userid(); //创建服务费的用户id
        $filed                = ['Img', 'Type', 'Note','Price','CorrelationId','ExpectedTime','TotalCost'];
        foreach ($filed as $key => $value) {
            if (isset($idata[$value])) {
                $rebate->$value = $idata[$value];
            }
        }
        //登记回款进度
        if(empty($idata['Price'])){
            $rebate->Limit = 0;
        }else{
            $rebate->Limit = bcdiv($idata['Price'],$idata['TotalCost'],4)*100;
        }
        //保存
        $rebate->save();
        return $rebate->RAPListId;
    }

    /**
     * 增加服务费费用
     * @param [type] $id    [description]
     * @param [type] $price [description]
     */
    public static function add_price($id, $price,$ExpectedTime = '')
    {
        $rebate        = RapList::get($id);
        $rebate->Price = bcadd($rebate->Price, $price,2);
        if($rebate->Price>0){
            $rebate->State = RapList::STATEING;
        }
        if(!empty($ExpectedTime)){
            $rebate->ExpectedTime = $ExpectedTime;
        }
        //返款比例 
        $rebate->Limit = bcdiv($rebate->Price,$rebate->TotalCost,4)*100;
        if($rebate->Limit==100){
            //返款完成后无需下次返款时间
            $rebate->State = RapList::STATEEND;
            $rebate->ExpectedTime = '';
        }
        $rebate->save();
        return sok();
    }

    /**
     * 判断服务费状态是否可操作
     * @param  [type] $list [id数组]
     * @return [type]       [返回错误代码]
     */
    public static function liststate($id,$type,$hidden=[],$hidloag=true,$jump = true,$type_state=true){
        if($type_state){
            $data = RapList::where('IsDelete','<>','1')->where('Type',$type)->where('CorrelationId',$id)->find();
        }else{
            $data = RapList::where('RapListId',$id)->find();
        }
        if(empty($data)){
            if($jump){
                return moerr('没有找到您需要的服务费信息');
            }else{
                return [];
            }
        }else{
            if($hidloag==true && Rolepower::ispower(204004) && $data['Type']=='contract'){
                $hidloag = false;
            }
            if($hidloag==true && Rolepower::ispower(204003) && $data['Type']=='hawaorder'){
                $hidloag = false;
            }

            if($hidloag){
                $hidden= array_merge(['OperationLog'],$hidden);
                $data = $data->hidden($hidden)->toArray();
            }elseif(empty($hidden)){
                $data = $data->toArray();
            }else{
                $data = $data->hidden($hidden)->toArray();    
            }
            return sok($data);
        }
    }

    /**
     * 获取创建关联信息/修改关联信息时候需要填写的数据
     * @param  [type] $id   [description]
     * @param  [type] $type [description]
     * @return [type]       [description]
     */
    public function get_view_info($id,$type){
        $data = self::liststate($id,$type,[],true,false);
        if(empty($data)){
            return [];
        }else{
            $rdata = $data['msg'];
            $rdata['StateText'] = RapList::getStatusText($rdata['State']);
            return $rdata;
        }
    }

    /**
     * 获取订单信息
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public static function getinfo($id,$usertype = 'buss'){
        if($usertype=='mana'){
            $data = self::liststate($id,'notype',[],false,true,false);
        }else{
            $data = self::liststate($id,'notype',[],true,true,false);
        }
        if (!$data['code']) { return $data; }
        $rdata = $data['msg'];
        $rdata['list'] = Rap::getlist($id,$usertype);
        $rdata['userinfo'] = User::getpublicinfo($rdata['CreateUserId']);
        $rdata['StateText'] = RapList::getStatusText($rdata['State']);
        return sok($rdata);
    }


    /**
     * 用户修改信息
     * @param  [type]  $data   [description]
     * @param  boolean $wtnote [是否记录]
     * @return [type]          [description]
     */
    public static function user_reinfo($data, $wtnote = true)
    {
        if (empty($data['id'])) {
            return moerr('缺少重要参数');
        }
        $info     = RapList::get($data['id']);
        if(empty($info)){
            return moerr('没有找到此条记录');
        }
        $userinfo = User::getinfo();
        $reinfo   = empty($info->OperationLog) ? '' : $info->OperationLog . "\n";
        $reinfo   = $reinfo . '【' . $userinfo->Name . '|' . $userinfo->UserId . '】在' . date('Y-m-d H:i', time()) . '进行了信息调整：';
        $nreinfo  = '';
        // dump($data);
        foreach ($data as $key => $value) {
            $sb = $info->getfiledname($key);
            if (empty($sb)) {
                continue;
            }
            //取原数据
            $ovalue = $info->$key;
            if ($key == 'State' && $value !== $ovalue) {
                $info->$key = $value;
                //value将改变成文字所以提前赋值
                $value   = $info->getStatusText((int) $value);
                $ovalue  = $info->getStatusText((int) $ovalue);
                $nreinfo = $nreinfo . '字段【' . $info->getfiledname($key) . '】由【' . $ovalue . '】修改为【' . $value . '】;' . "\n";
            }else if ($key == 'TotalCost' && $value !== $ovalue) {
                $info->$key = $value;
                //登记回款进度
                if(empty($info->Price)){
                    $info->Limit = 0;
                }else{
                    $info->Limit = bcdiv($info->Price,$value,4)*100;
                }
                $nreinfo = $nreinfo . '字段【' . $info->getfiledname($key) . '】由【' . $ovalue . '】修改为【' . $value . '】;' . "\n";
            }else if (isset($value) && $ovalue !== $value) {                
                $nreinfo    = $nreinfo . '字段【' . $info->getfiledname($key) . '】由【' . $ovalue . '】修改为【' . $value . '】;' . "\n";
                $info->$key = $value;
            }
        }
        if (!empty($nreinfo)) {
            if ($wtnote) {
                $reinfo             = $reinfo . "\n" . $nreinfo;
                $info->OperationLog = $reinfo;
            }
            $info->save();
        } else {
            return moerr('没有找到需要调整的数据');
        }
    }

    /**
     * 获取字段的名字，同时仅可删除带名字的字段
     * @param  [type] $str [description]
     * @return [type]      [description]
     */
    public static function getfiledname($str)
    {
        $filename = [
            'Note'  => '备注', 'Img'      => '图片备注', 'ExpectedTime'=>'预计回款时间','TotalCost'=>'总金额',
            'State' => '状态', 'IsDelete' => '是否删除'
            //, 'Limit' => '回款比例','Price' =>'合计服务费费用'
        ];
        if (empty($filename[$str])) {
            return false;
        }
        return $filename[$str];
    }

}
